<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑页面' : '新建页面'"
    width="800px"
    :before-close="handleClose"
  >
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 基本信息选项卡 -->
      <el-tab-pane label="基本信息" name="basic">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="80px"
          @submit.prevent
        >
          <el-form-item label="页面名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入页面名称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
          
          <el-form-item label="页面描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="请输入页面描述"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
          
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :value="1">启用</el-radio>
              <el-radio :value="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 关系管理选项卡 - 仅在编辑模式下显示 -->
      <el-tab-pane v-if="isEdit" label="关系管理" name="relations">
        <div class="relation-management">
          <!-- 当前归属分类 -->
          <div class="relation-section">
            <h4>当前归属分类</h4>
            <div class="current-categories">
              <el-tag
                v-for="category in currentCategories"
                :key="category.id"
                closable
                @close="removeCategory(category.id)"
                type="success"
                class="category-tag"
              >
                {{ category.name }}
              </el-tag>
              <el-tag v-if="currentCategories.length === 0" type="info">
                暂无归属分类
              </el-tag>
            </div>
          </div>

          <!-- 添加分类 -->
          <div class="relation-section">
            <h4>添加分类</h4>
            <div class="add-category-section">
              <el-select
                v-model="selectedCategoryId"
                placeholder="请选择要添加的分类"
                style="width: 300px; margin-right: 10px;"
                filterable
              >
                <el-option
                  v-for="category in availableCategories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                >
                  <span>{{ category.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ category.description || '无描述' }}
                  </span>
                </el-option>
              </el-select>
              <el-button 
                type="primary" 
                @click="addCategory"
                :disabled="!selectedCategoryId"
              >
                添加分类
              </el-button>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, nextTick, defineProps, defineEmits, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDataStore } from '../composables/useDataStore.js'

// 获取全局数据状态
const { categories: globalCategories } = useDataStore()

// 在 setup 函数中获取组件实例
const instance = getCurrentInstance()

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Events
const emit = defineEmits([
  'update:visible', 
  'save', 
  'cancel',
  'add-category-relation',
  'remove-category-relation'
])

// 响应式数据
const formRef = ref()
const saving = ref(false)
const activeTab = ref('basic')
const selectedCategoryId = ref(null)



/**
 * 页面表单数据
 */
const form = ref({
  id: null,
  name: '',
  description: '',
  status: 1
})

/**
 * 当前页面归属的分类列表
 */
const currentCategories = ref([])

/**
 * 强制刷新标志
 */
const forceRefresh = ref(0)



/**
 * 可添加的分类列表（排除已归属的分类）
 */
const availableCategories = computed(() => {
  // 使用全局categories数据
  const categoriesSource = globalCategories.value || []
  
  if (!Array.isArray(categoriesSource) || categoriesSource.length === 0) {
    return []
  }
  
  const currentCategoryIds = currentCategories.value.map(cat => cat.id)
  return categoriesSource.filter(cat => !currentCategoryIds.includes(cat.id))
})

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

/**
 * 表单验证规则
 */
const rules = {
  name: [
    { required: true, message: '请输入页面名称', trigger: 'blur' },
    { min: 1, max: 100, message: '页面名称长度应在 1 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '页面描述不能超过 500 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择页面状态', trigger: 'change' }
  ]
}

/**
 * 重置表单数据
 */
const resetForm = () => {
  form.value = {
    id: null,
    name: '',
    description: '',
    status: 1
  }
  currentCategories.value = []
  selectedCategoryId.value = null
  activeTab.value = 'basic'
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

/**
 * 处理表单数据的函数
 */
const processFormData = (newData) => {
  console.log('🔍 PageForm - 处理表单数据:', newData)
  console.log('🔍 PageForm - isEdit:', props.isEdit)
  console.log('🔍 PageForm - visible:', props.visible)
  
  if (newData && Object.keys(newData).length > 0) {
    form.value = {
      id: newData.id || null,
      name: newData.name || '',
      description: newData.description || '',
      status: newData.status !== undefined ? newData.status : 1
    }
    
    // 如果是编辑模式，加载当前页面的分类关系
    if (props.isEdit && newData.categories) {
      currentCategories.value = [...newData.categories]
      console.log('🔍 PageForm - 编辑模式，设置 currentCategories:', currentCategories.value.length)
    } else {
      // 新建模式，重置分类关系
      currentCategories.value = []
      console.log('🔍 PageForm - 新建模式，重置 currentCategories')
    }
  } else {
    resetForm()
  }
}

/**
 * 监听表单数据变化
 */
watch(
  () => props.formData,
  (newData) => {
    console.log('🔍 PageForm - formData 变化:', newData)
    
    // 如果表单可见，立即处理数据
    if (props.visible) {
      processFormData(newData)
    }
    // 如果表单不可见，数据会在visible变化时处理
  },
  { immediate: true, deep: true }
)

/**
 * 监听表单可见性变化
 */
watch(
  () => props.visible,
  (newVisible) => {
    console.log('🔍 PageForm - visible 变化:', newVisible)
    
    if (newVisible) {
      // 表单显示时，处理当前的formData
      processFormData(props.formData)
      
      // 重置表单状态
      activeTab.value = 'basic'
      selectedCategoryId.value = null
    }
  },
  { immediate: true }
)

/**
 * 监听 allCategories 属性变化
 */
watch(
  () => props.allCategories,
  (newCategories, oldCategories) => {
    console.log('🔍 PageForm - allCategories 属性变化:', newCategories?.length || 0, '项')
    console.log('🔍 PageForm - allCategories 内容:', newCategories?.slice(0, 2))
    console.log('🔍 PageForm - allCategories 完整数据:', JSON.stringify(newCategories, null, 2))
    console.log('🔍 PageForm - oldCategories 长度:', oldCategories?.length || 0)
    
    // 当从空变为有数据时，强制刷新 availableCategories
    if ((!oldCategories || oldCategories.length === 0) && newCategories && newCategories.length > 0) {
      console.log('✅ PageForm - allCategories 有数据，强制刷新 availableCategories')
      forceRefresh.value++
    }
  },
  { immediate: true, deep: true }
)

/**
 * 监听表单可见性变化
 */
// watch(
//   () => props.visible,
//   async (newVisible) => {
//     console.log('🔍 PageForm - visible 属性变化:', newVisible)
    
//     if (newVisible) {
//       console.log('🔍 PageForm - 表单显示时 allCategories 长度:', props.allCategories?.length || 0)
//       console.log('🔍 PageForm - 表单显示时 allCategories 内容:', JSON.stringify(props.allCategories?.slice(0, 2), null, 2))
      
//       // 等待Vue响应式系统完成更新
//       await nextTick()
//       console.log('🔍 PageForm - nextTick 后 allCategories 长度:', props.allCategories?.length || 0)
      
//       // 如果数据仍然为空，进行多次检查
//       if (!props.allCategories || props.allCategories.length === 0) {
//         console.log('⚠️ PageForm - allCategories 为空，开始轮询检查')
        
//         for (let i = 0; i < 20; i++) {
//           await new Promise(resolve => setTimeout(resolve, 50))
//           console.log(`🔍 PageForm - 第${i+1}次检查 allCategories 长度:`, props.allCategories?.length || 0)
          
//           if (props.allCategories && props.allCategories.length > 0) {
//             console.log('✅ PageForm - allCategories 数据已准备好')
//             forceRefresh.value++
//             break
//           }
//         }
        
//         if (!props.allCategories || props.allCategories.length === 0) {
//           console.error('❌ PageForm - allCategories 数据始终为空')
//         }
//       }
      
//       // 重置表单状态
//       activeTab.value = 'basic'
//       selectedCategoryId.value = null
//     }
//   },
//   { immediate: true }
// )

/**
 * 监听 allCategories 和 visible 的组合变化
 */
// watch(
//   () => [props.allCategories, props.visible],
//   ([newCategories, newVisible]) => {
//     if (newVisible && newCategories && newCategories.length > 0) {
//       console.log('✅ PageForm - allCategories 和 visible 都准备好了')
//       console.log('🔍 PageForm - 组合监听 - allCategories 长度:', newCategories.length)
//       console.log('🔍 PageForm - 组合监听 - currentCategories 长度:', currentCategories.value?.length || 0)
      
//       // 强制刷新 availableCategories
//       console.log('🔄 PageForm - 组合监听触发强制刷新')
//       forceRefresh.value++
//     }
//   },
//   { immediate: true, deep: true }
// )

/**
 * 添加分类关系
 */
const addCategory = async () => {
  if (!selectedCategoryId.value) return
  
  // 使用相同的数据源策略
  const categoriesSource = (globalCategories.value && globalCategories.value.length > 0) 
    ? globalCategories.value 
    : props.allCategories
  
  const selectedCategory = categoriesSource.find(cat => cat.id === selectedCategoryId.value)
  if (!selectedCategory) return
  
  try {
    // 检查是否已存在
    if (currentCategories.value.some(cat => cat.id === selectedCategoryId.value)) {
      ElMessage.warning('该分类已存在')
      return
    }
    
    // 添加到当前分类列表
    currentCategories.value.push(selectedCategory)
    
    // 触发事件通知父组件
    emit('add-category-relation', {
      pageId: form.value.id,
      categoryId: selectedCategoryId.value
    })
    
    selectedCategoryId.value = null
    ElMessage.success('分类添加成功')
  } catch (error) {
    console.error('添加分类失败:', error)
    ElMessage.error('添加分类失败')
  }
}

/**
 * 移除分类关系
 */
const removeCategory = async (categoryId) => {
  try {
    await ElMessageBox.confirm(
      '确定要移除该分类关系吗？',
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 从当前分类列表中移除
    currentCategories.value = currentCategories.value.filter(cat => cat.id !== categoryId)
    
    // 触发事件通知父组件
    emit('remove-category-relation', {
      pageId: form.value.id,
      categoryId: categoryId
    })
    
    ElMessage.success('分类移除成功')
  } catch (error) {
    // 用户取消操作
    if (error !== 'cancel') {
      console.error('移除分类失败:', error)
      ElMessage.error('移除分类失败')
    }
  }
}

/**
 * 处理保存操作
 */
const handleSave = async () => {
  console.log('🔍 PageForm - handleSave 开始执行')
  console.log('🔍 PageForm - formRef.value:', formRef.value)
  console.log('🔍 PageForm - emit 函数:', emit)
  console.log('🔍 PageForm - props.visible:', props.visible)
  console.log('🔍 PageForm - 当前组件实例 ID:', Math.random().toString(36).substr(2, 9))
  
  // 添加父组件信息检测
  console.log('🚨🚨🚨 PageForm - 检查父组件上下文 🚨🚨🚨')
  console.log('🔍 PageForm - $parent:', instance?.parent)
  console.log('🔍 PageForm - 父组件类型:', instance?.parent?.type?.name || instance?.parent?.type?.__name || '未知')
  console.log('🔍 PageForm - 父组件完整信息:', instance?.parent?.type)
  
  if (!formRef.value) {
    console.log('❌ PageForm - formRef.value 为空，退出')
    return
  }
  
  try {
    console.log('🔍 PageForm - 开始表单验证')
    await formRef.value.validate()
    console.log('✅ PageForm - 表单验证通过')
    
    saving.value = true
    
    const formData = { 
      ...form.value,
      categories: currentCategories.value
    }
    
    console.log('🔍 PageForm - 准备发送的表单数据:', formData)
    console.log('🔍 PageForm - isEdit 参数:', props.isEdit)
    console.log('🔍 PageForm - 即将触发 save 事件')
    console.log('🔍 PageForm - emit 函数类型:', typeof emit)
    
    // 尝试触发 save 事件
    try {
      console.log('🚨🚨🚨 PageForm - 正在调用 emit(save) 🚨🚨🚨')
      console.log('🔍 PageForm - 检查组件实例的事件监听器')
      console.log('🔍 PageForm - 组件实例:', instance)
      console.log('🔍 PageForm - 组件vnode:', instance?.vnode)
      console.log('🔍 PageForm - 组件props:', instance?.vnode?.props)
      console.log('🔍 PageForm - 事件监听器:', instance?.vnode?.props ? Object.keys(instance.vnode.props).filter(key => key.startsWith('on')) : '无')
      
      emit('save', formData, props.isEdit)
      console.log('✅ PageForm - save 事件已触发，参数:', { formData, isEdit: props.isEdit })
      console.log('🚨🚨🚨 PageForm - emit(save) 调用完成 🚨🚨🚨')
    } catch (emitError) {
      console.error('❌ PageForm - emit 调用失败:', emitError)
    }
    
    ElMessage.success(props.isEdit ? '页面更新成功' : '页面创建成功')
  } catch (error) {
    console.error('❌ PageForm - 表单验证失败:', error)
    ElMessage.error('请检查表单填写是否正确')
  } finally {
    saving.value = false
    console.log('🔍 PageForm - handleSave 执行完成')
  }
}

/**
 * 处理关闭对话框
 */
const handleClose = () => {
  emit('cancel')
  resetForm()
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 120px;
}

:deep(.el-input-group__prepend) {
  background-color: #f5f7fa;
  color: #909399;
  border-color: #dcdfe6;
}

/* 关系管理样式 */
.relation-management {
  padding: 20px;
}

.relation-section {
  margin-bottom: 30px;
}

.relation-section h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.current-categories {
  min-height: 40px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.category-tag {
  margin: 4px 8px 4px 0;
  font-size: 13px;
}

.add-category-section {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-tab-pane) {
  padding: 20px;
}

/* 选择器样式优化 */
:deep(.el-select .el-input__inner) {
  height: 36px;
}

/* 标签样式优化 */
:deep(.el-tag.el-tag--success) {
  background-color: #f0f9ff;
  border-color: #67c23a;
  color: #67c23a;
}

:deep(.el-tag.el-tag--info) {
  background-color: #f4f4f5;
  border-color: #909399;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-category-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .add-category-section .el-select {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 10px;
  }
}
</style>